import datetime
import json
import os,shutil

import time
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.http import HttpResponse
from django.shortcuts import render_to_response
from PolicyData.PolicyControl import policy as policy_class
from Common import sql_content,Fession_mini
from PublicChartDisplay.chartDisplayControl.user import area as area_class, salary as salary_class, area_map, analysis, demo_mag, \
    undefined_4
from PublicChartDisplay.models import Chart
from PublicChartDisplay import models
from django.db.models import Count
from django.conf import settings
from django import forms

# Create your views here.
def gocharDisplay(request):
    formData = dict(list(Chart.objects.filter(chartid=1).values())[0])
    print('formdata', formData)
    meg_fill, page = getScript('1')
    return render_to_response('admin/chartDisplay.html',{'allData':Chart.objects.all().values(),'formData':formData,'Message': meg_fill, 'page':page})
def returnTable(request):
    origin = {"code": 0, "msg": "", "count": 0, "data": []}
    origin["count"] = Chart.objects.all().values().count() #查询数据总数
    origin["data"] = list(Chart.objects.all().values()) #models查询所有数据
    print(Chart.objects.all().values('chartstate'))
    if origin["data"] is not None:
        for i in origin["data"]:
            i['publictime'] = datetime.datetime.strftime(i['publictime'],'%Y-%m-%d %H:%M:%S')
    if request.GET.get('key') is not None:
        if request.GET.get('key') == 'changeSwitch':
            chid = request.GET.get('name')
            choice = int(request.GET.get('chartid'))
            models.Chart.objects.filter(chartid=chid).update(chartstate=choice)
        else:
            print(request.GET.get('chartid'))
            id = request.GET.get('chartid')
            formData = dict(list(Chart.objects.filter(chartid=id).values())[0])
            print('formdata',formData)
            if id != '9':
                meg_fill, page = getScript(str(formData['chartid']))
            if id == '9':
                meg_fill={}
                page = {}
            return render_to_response('admin/chartDisplay.html', {'allData': Chart.objects.all().values(),'formData':formData,'Message': meg_fill, 'page':page})

    return HttpResponse(json.dumps(origin))

def mappingCS(request):
    if request.method == "POST":
        tag = request.POST.get('tag')
        title = request.POST.get('title')
        abstract = request.POST.get('abstract')
        chartdescription = request.POST.get('chartdescription')
        if request.POST.get('chartstate') is not None:
            chartstate = 1
        else:
            chartstate = 0
        testURL = "D://biyeproject//JobProject//PublicChartDisplay//static//migrateFile"
        IMGtagURL = "D://biyeproject//JobProject//static//images//content//300//"
        JStagURL = "D://biyeproject//JobProject//PublicChartDisplay//static//"
        ScripttagURL = "D://biyeproject//JobProject//PublicChartDisplay//chartDisplayControl//user//"
        exhibitImgFession = Fession_mini.getFessionMini('upload')['exhibitImg']
        chartjsFession = Fession_mini.getFessionMini('upload')['chartjs']
        chartscriptFession = Fession_mini.getFessionMini('upload')['chartscript']
        try:
            if default_storage.exists(IMGtagURL + exhibitImgFession) is False:
                shutil.move(testURL + exhibitImgFession, IMGtagURL)
            else:
                default_storage.delete(testURL + exhibitImgFession)
            if default_storage.exists(JStagURL + chartjsFession) is False:
                shutil.move(testURL + chartjsFession,JStagURL)
            else:
                default_storage.delete(testURL + chartjsFession)
            if default_storage.exists(ScripttagURL + chartscriptFession) is False:
                shutil.move(testURL + chartscriptFession,ScripttagURL)
            else:
                default_storage.delete(testURL + chartscriptFession)
        except:
            print("PublicCharDisplay-view.py 文件迁移异常"+time.localtime(time.time()))
        try:
            ch = Chart()
            ch.tag = tag
            ch.title = title
            ch.abstract = abstract
            ch.chartjs = Fession_mini.getFessionMini('upload')['chartjs']
            ch.chartscript = Fession_mini.getFessionMini('upload')['chartscript']
            ch.charlog = 1
            ch.chartstate = chartstate
            ch.author = request.session['LoginName_session']
            ch.publictime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
            ch.chartdescription = chartdescription
            ch.exhibitionimg = Fession_mini.getFessionMini('upload')['exhibitImg']
            ch.save()
        except:
            print("PublicCharDisplay-view.py 数据库存储异常异常" + time.localtime(time.time()))

    return render_to_response('admin/chartManage.html')

def returnUpload(request):
    remeg = {"code": 1, "msg": "", "data": {"src": ""}} #回调JSON
    if request.method == "POST":
        if request.FILES is not None: #<MultiValueDict: {'file': [<InMemoryUploadedFile: -6231968e10e2937c.jpg (image/jpeg)>]}>
            #临时存储文件路径
            tmpURL = 'D://biyeproject//JobProject//PublicChartDisplay//static//migrateFile//'
            Filetage = request.FILES.get('file') #-6231968e10e2937c.jpg
            #下载图片
            if Filetage.name.find('.jpg')>0:
                try:
                    if default_storage.exists(tmpURL + Filetage.name):
                        default_storage.delete(tmpURL + Filetage.name)
                    Imgpath = default_storage.save(tmpURL + Filetage.name,
                        ContentFile(Filetage.read()))
                    os.path.join(settings.MEDIA_ROOT, Imgpath)
                    upload = Fession_mini.getFessionMini("upload")
                    upload["exhibitImg"] = Filetage.name
                    Fession_mini.setFessionMini("upload",upload)
                    remeg['code'] = 0
                except:
                    remeg['code']=1
            # 下载脚本
            elif Filetage.name.find('.py')>0:
                try:
                    if default_storage.exists(tmpURL + Filetage.name):
                        default_storage.delete(tmpURL + Filetage.name)
                    Pypath = default_storage.save(tmpURL + Filetage.name,
                        ContentFile(Filetage.read()))
                    os.path.join(settings.MEDIA_ROOT, Pypath)
                    upload = Fession_mini.getFessionMini("upload")
                    upload["chartscript"] = Filetage.name
                    Fession_mini.setFessionMini("upload", upload)
                    remeg['code'] = 0
                    remeg['name'] = Filetage.name
                except:
                    remeg['code'] = 1
            # 下载js
            elif Filetage.name.find('.js')>0:
                try:
                    if default_storage.exists(tmpURL + Filetage.name):
                        default_storage.delete(tmpURL + Filetage.name)
                    JSpath = default_storage.save(tmpURL+ Filetage.name,
                        ContentFile(Filetage.read()))
                    os.path.join(settings.MEDIA_ROOT, JSpath)
                    upload = Fession_mini.getFessionMini("upload")
                    upload["chartjs"] = Filetage.name
                    Fession_mini.setFessionMini("upload", upload)
                    remeg['code'] = 0
                    remeg['name'] = Filetage.name
                except:
                    remeg['code'] = 1
    print(Fession_mini.getFessionMini("upload"))
    return HttpResponse(json.dumps(remeg))



def getScript(id):
    # 就业数据，all，1@前10大岗位数量最多的城市
    if id == '1':
        return area_class.Job_place().name_main()
    # 就业数据，all，2@部分城市工资情况
    elif id == '2':
        return salary_class.Salary_place().name_main()
    elif id == '3':
        return area_map.Job_map().name_main()
    elif id == '4':
        return undefined_4.Undefined_4().name_main()
    elif id == '5':
        return undefined_4.Undefined_4().name_main()
    elif id == '6':
        return undefined_4.Undefined_4().name_main()
    elif id == '7':
        return undefined_4.Undefined_4().name_main()
    elif id == '8':
        return undefined_4.Undefined_4().name_main()

    elif id == '9':
        page = {'title': '就业岗位最多的前10个城市',
         'int': '\n                    大多数的人一开始选择的城市就是自己奋斗一生的城市，据了解，七成的职场白领轻易不会放弃自己已经积累的事业基础和人脉关系，轻易不会更换城市，除非另外一个城市会有更好的发展或者有爱情的吸引。因此，每个人在选择一个城市的时候无不经过深思熟虑，那么，参与调查的白领最心仪的就业城市是哪几个呢？\n\u3000\u3000“大学生就业向往城市排名”前十名分别为：上海（15.12％）、北京（14.53％）、杭州（8.72％）、广州（7.56％）、深圳（6.40％）、成都（6.40％）、大连（4.65％）、苏州（4.65％）、青岛（4.07％）、武汉（3.49％）、西安（3.49％）、厦门（3.49％）。\n\u3000\u3000随着近几年的迅速发展和人们就业观念的转变，杭州成为继上海、北京之后深受白领欢迎的就业城市，广州、深圳不复当年风光，跌出前三甲。被某周刊评为“中国第五城”的成都，因其人杰地灵、美食＋美女，吸引了众多白领，和深圳并列第五名。',
         'type': '毕业生,就业岗位, 10大城市, 图标, 饼状图', 'unknow': 'view', 'date': '2019/5/20',
         'list': {'小米招聘': 'www', '华为招聘': 'www', '阿里招聘': 'www', '百度招聘': 'www', '51招聘': 'www'}}
        meg_fill = {}
        return meg_fill,page
#user - 普通用户
#will display all chart.
def new_showChart_entire(request):
    # policy_fill = policy_class._Policy(1, 10).name_main()
    data = Chart.objects.all().values()
    print(data)
    mag_Dict = demo_mag._demo_mag().showData_demo(data)
    return render_to_response('user/exhibiteData.html', {'mag_Dict': mag_Dict})

# def showData_school(request):
#     mag_Dict = demo_mag._demo_mag().showData_demo()
#     return render_to_response('user/showData_demo.html', {'mag_Dict': mag_Dict})
# def showData_society(request):
#     mag_Dict = demo_mag._demo_mag().showData_demo()
#     return render_to_response('user/showData_demo.html', {'mag_Dict': mag_Dict})
# def showData_all(request):
#     mag_Dict = demo_mag._demo_mag().showData_demo()
#     return render_to_response('user/showData_demo.html', {'mag_Dict': mag_Dict})
# def showData_policy(request):
#     mag_Dict = demo_mag._demo_mag().showData_demo()
#     return render_to_response('user/showData_demo.html', {'mag_Dict': mag_Dict})

def details(request):
    if request.method == "POST":
        # 就业数据，all，1@前10大岗位数量最多的城市
        if request.POST.get('hidDetail')=='1':
            demo = 1
            meg_fill,page = area_class.Job_place().name_main()
        # 就业数据，all，2@部分城市工资情况
        elif request.POST.get('hidDetail')=='2':
            demo = 2
            meg_fill, page = salary_class.Salary_place().name_main()
        elif request.POST.get('hidDetail') == '3':
            demo = 3
            meg_fill, page = area_map.Job_map().name_main()
        elif request.POST.get('hidDetail') == '4':
            demo = 4
            meg_fill, page = undefined_4.Undefined_4().name_main()
            print('views_details_html', meg_fill)
        elif request.POST.get('hidDetail') == '5':
            demo = 5
            meg_fill, page = undefined_4.Undefined_4().name_main()
            print('views_details_html', meg_fill)
        elif request.POST.get('hidDetail') == '9':
            demo = 9
            page = {'title': '这只是一个测试啊啊 啊',
                    'int': '这只是一个测试啊啊 啊这只是一个测试啊啊 啊这只是一个测试啊啊 啊这只是一个测试啊啊 啊',
                    'type': '测试 测试 测试', 'unknow': 'view', 'date': '刚刚',
                    'list': {'小米招聘': 'www', '华为招聘': 'www', '阿里招聘': 'www', '百度招聘': 'www', '51招聘': 'www'}}
            meg_fill = {}
            print('views_details_html', meg_fill)

        return render_to_response('user/showData_details_demo.html', {'demo':demo,'Message': meg_fill, 'page':page})
    return None

def analysis_school(request):
    return render_to_response('user/analysis_demo.html')
def analysis_society(request):
    return render_to_response('user/analysis_demo.html')
def analysis_all(request):
    if request.method == "GET":
        data_count = sql_content.sql_content().data_count("select count(*) from data_collection.data_51job_she;")
        page_size = 30
        now_page = 1
        page_begin = 1
        page_end = 30
        end_page_begin = 0
        if (data_count % page_size == 0):
            page_count = data_count / page_size
        else:
            page_count = data_count // page_size + 1
            end_page_begin = data_count // page_size * page_size + 1
            # print(page_count,end_page_begin)
        if(request.GET.get('hidPageIndex') is not None):
            now_page = int(request.GET.get('hidPageIndex'))
            page_end = now_page * page_size
            page_begin = page_end - page_size + 1
            if(page_end > data_count):
                page_end = data_count
        page_count_list = []
        for num in range(1,page_count+1):
            page_count_list.append(num)
        print(page_begin,page_end)
        analysis_fill = analysis._Analysis().analysis_sql(page_begin,page_end)
        page_meg = {'page_count':page_count , 'page_count_list':page_count_list,'now_page':now_page}
        print('views_analysis_fill_modth', analysis_fill)
        return render_to_response('user/analysis_demo.html', {'Analysis': analysis_fill,'page_meg':page_meg})
    elif request.method == "POST":
        print('this is Post!')
        now_id = int(request.POST.get('hidDetail'))
        if (now_id is not None):
            detail_fill = analysis._Analysis().analysis_sql_id(now_id)
            return render_to_response('user/analysis_allData_demo.html',{'detail_fill':detail_fill})

    else:
        return render_to_response('user/analysis_allData_demo.html')



#DACHUANGKAIYE
def index1(request):
    demo = 1
    meg_fill, page = area_class.Job_place().name_main()
    return render_to_response('user/showData_details_demo.html', {'demo': demo, 'Message': meg_fill, 'page': page})
def index2(request):
    detail_fill = policy_class._Policy(0, 0).policy_sql_id(17)
    return render_to_response('policy_demo.html', {'detail_fill': detail_fill})
def index3(request):
    pass
def index4(request):
    now_id = int(time.strftime('%d', time.localtime(time.time())))
    detail_fill = analysis._Analysis().analysis_sql_id(now_id)
    return render_to_response('user/analysis_allData_demo.html', {'detail_fill': detail_fill})
def index1_2(request):
    demo = 3
    meg_fill, page = area_map.Job_map().name_main()
    return render_to_response('user/showData_details_demo.html', {'demo': demo, 'Message': meg_fill, 'page': page})
def index1_3(request):
    demo = 2
    meg_fill, page = salary_class.Salary_place().name_main()
    return render_to_response('user/showData_details_demo.html', {'demo': demo, 'Message': meg_fill, 'page': page})
def index1_4(request):
    demo = 4
    meg_fill, page = undefined_4.Undefined_4().name_main()
    return render_to_response('user/showData_details_demo.html', {'demo': demo, 'Message': meg_fill, 'page': page})
def index5(request):
    now_id = int(time.strftime('%S', time.localtime(time.time())))
    detail_fill = policy_class._Policy(0, 0).policy_sql_id(now_id)
    return render_to_response('policy_demo.html', {'detail_fill': detail_fill})